import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/goods/goods_obj.dart';
import 'package:xws/state/user_state.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/dio_utils/request/goods_req.dart';
import 'package:xws/widgets/goods_config/goods_detail/detail_page.dart';
import 'package:xws/widgets/refresh_widget/refresh_load_view.dart';
import 'package:xws/widgets/safe_scaffold.dart';

import 'edit_goods.dart';
import 'my_goods_item.dart';

/// 发布的物品
class MyPub extends StatefulWidget {
  const MyPub({Key? key}) : super(key: key);

  @override
  _MyPubState createState() => _MyPubState();
}

class _MyPubState extends State<MyPub> with SafeState<MyPub> {
  late RefreshViewController<GoodsObj> _viewController;

  @override
  void initState() {
    super.initState();
    _viewController = RefreshViewController<GoodsObj>();
  }

  @override
  void dispose() {
    _viewController.dispose();
    super.dispose();
  }

  /// 删除
  Future<void> _del(int index, GoodsObj g) async {
    final bool? cr = await tips('确认删除?');

    if (cr == null || !cr) return;

    loading(context);
    final bool r = await delGoods(g.id);
    close(context);

    if (r) {
      st('删除成功');
      _viewController.remove(index);
      us.updateBasicInfo();
    }
  }

  /// 编辑或查看
  Future<void> _edit(GoodsObj gds, int index) async {
    if (gds.status == GoodsStatus.DELIVERED) {
      await push<bool>(context, DetailPage(goods: gds, index: index));
    } else {
      final GoodsObj? g = await push<GoodsObj>(context, EditGoods(goods: gds));
      if (g != null) {
        gds.updateFrom(g);
        _viewController.setState();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      titleText: '我发布的',
      body: RefreshLoadView<GoodsObj>(
        viewController: _viewController,
        type: ViewType.grid,
        itemBuilder: (int index, GoodsObj g) => MyGoodsItem(
          index: index,
          goods: g,
          onTap: () => _edit(g, index),
          onDel: g.status == GoodsStatus.SHOWING ? () => _del(index, g) : null,
        ),
        padding: const EdgeInsets.all(20),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          crossAxisCount: 2,
          childAspectRatio: 0.9,
        ),
        onRefresh: (_, __) async {
          return getGoodsList(
            pageNum: 1,
            searchType: GoodsSearchType.OWNER,
          );
        },
        onLoad: (int page, __) async {
          return getGoodsList(
            pageNum: page,
            searchType: GoodsSearchType.OWNER,
          );
        },
      ),
    );
  }
}
